package colaborativo.ondefica;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.bonuspack.overlays.Marker.OnMarkerDragListener;
import org.osmdroid.bonuspack.overlays.MarkerInfoWindow;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	MapView map;
	IMapController mapController;
	private Timer myTimer;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);		
		myTimer = new Timer();
		myTimer.schedule(new TimerTask() {			
			@Override
			public void run() {
				TimerMethod();
			}			
			
		}, 0, 5000);
		
		
		map = (MapView) findViewById(R.id.map);
		map.setTileSource(TileSourceFactory.MAPNIK);
		map.setBuiltInZoomControls(true);
		map.setMultiTouchControls(true);				
		GeoPoint startPoint = new GeoPoint(-3.08923,-59.96453);
		mapController = map.getController();
		mapController.setZoom(18);
		mapController.setCenter(startPoint);						
		map.setOnTouchListener(new OnTouchListener() {			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Boolean control = true;				
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
				    case MotionEvent.ACTION_DOWN:						    	
				        v.setPressed(true);	
				        control = false;
				        break;
				    case MotionEvent.ACTION_UP:
				    	control = false;
				    	break;
				    case MotionEvent.ACTION_OUTSIDE:
				        v.setPressed(false);
				        new MyAsyncTask().execute("teste");
				        // Codigo se o tempo pressionando				        				        
				        break;
				    case MotionEvent.ACTION_MOVE:				    	
				    	v.setPressed(false);
				    	control = false;
				        break;
				    case MotionEvent.ACTION_POINTER_UP:
				        break;					   
			    }
				
				return control;
			}
		});		
		
		
	}	
	
	private void TimerMethod() {
		
		this.runOnUiThread(Timer_Tick);
	}
	
	private Runnable Timer_Tick = new Runnable() {
		public void run() {				
			new MyAsyncTask().execute("teste");
		}
	};
	
	@Override
	protected void onResume(){
		super.onResume();
        new MyAsyncTask().execute("teste");		
	}
	
	//------------------------criar evento-------------------------------
	 
	public void criarEvento(View view) {		
		Intent intent = new Intent(this, CriarEvento.class);
		
		IGeoPoint x =  map.getProjection().fromPixels(map.getWidth()/2, map.getHeight()/2);
				
		Log.d("M.Debug", x.getLatitude() +"/"+x.getLongitude());
		Bundle pontos = new Bundle();
		
		pontos.putDouble("xcenter", x.getLatitude());		
		pontos.putDouble("ycenter", x.getLongitude());
		intent.putExtras(pontos);
		startActivity(intent);
		
	}
	
	//------------------------login--------------------------------------
	private AlertDialog teladialogo;
	 
	public void login(View v) {
		
		/*	LayoutInflater li = getLayoutInflater();
		View view = li.inflate(R.layout.telalogin, Login.class);
		
		
		view.findViewById(R.id.entrar).setOnClickListener(new View.OnClickListener() 
		{ 
			public void onClick(View arg0) {
			Toast.makeText(MainActivity.this, 
					"Logado", Toast.LENGTH_SHORT).show();
				} 
		});
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this); 
		
		builder.setView(view); 
		teladialogo = builder.create(); 
		teladialogo.getWindow().setBackgroundDrawable(new
				ColorDrawable(android.graphics.Color.TRANSPARENT));
		teladialogo.show();*/
		
		Intent intent = new Intent(this, Logar.class);
		startActivity(intent);
			
	}
	
	//------------------------criar login--------------------------------
	public void criarLogin(View view) {
		Intent intent = new Intent(this, CriarLogin.class);
		startActivity(intent);
	}
	
	//------------------------menu--------------------------------------
	
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		
		return true;
	}
	
	private AlertDialog telasobre;
	
	public boolean onOptionsItemSelected(MenuItem item) {	
		
		switch (item.getItemId()) {
			case R.id.item1:
				LayoutInflater li2 = getLayoutInflater();
				View view = li2.inflate(R.layout.sobre, null);
				
				AlertDialog.Builder builder = new AlertDialog.Builder(this); 
				
				builder.setView(view); 
				telasobre = builder.create(); 
				telasobre.getWindow().setBackgroundDrawable(new
						ColorDrawable(android.graphics.Color.TRANSPARENT));
				telasobre.show();
			    return true;
			
			default:
			    return super.onOptionsItemSelected(item);
		}
		
	}
	
	class OnMarkerDragListenerDrawer implements OnMarkerDragListener {			
		ArrayList<GeoPoint> mTrace = new ArrayList<GeoPoint>(200);
		@Override public void onMarkerDrag(Marker marker) {				
			mTrace.add(marker.getPosition());				
		}
		@Override public void onMarkerDragEnd(Marker marker) {				
			Polyline p = new Polyline(map.getContext());
			p.setColor(0xAA0000FF);
			p.setWidth(2.0f);
			p.setPoints(mTrace);				
			map.getOverlays().add(p);
			map.invalidate();		
		}
		@Override public void onMarkerDragStart(Marker marker) {
			mTrace.add(marker.getPosition());				
		}
	}
	
	private void plot_points(JSONArray pontos){				
		Drawable poiIcon = getResources().getDrawable(R.drawable.marker_poi_default);
		if(pontos!=null){
    		for(int i = 0;i<pontos.length();i++){
    			try{
    				Marker pto = new Marker(map);
    				pto.setPosition(new GeoPoint( pontos.getJSONObject(i).getInt("latitute"), pontos.getJSONObject(i).getInt("longitude")));
    				pto.setAnchor(Marker.ANCHOR_CENTER, 1.0f);
    				pto.setIcon(poiIcon);
    				pto.setInfoWindow(new CustomInfoWindow(map, pontos.getJSONObject(i)));
    				pto.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
    				Log.d("opMap.ResultadosMarcadores", pontos.getJSONObject(i).getString("nomeLocal"));
    				pto.setTitle(pontos.getJSONObject(i).getString("nomeLocal"));
    				map.getOverlays().add(pto);
    			}catch(JSONException e){				
    			}			
    		}
    		map.invalidate();
		}
	}
	
	//7. Customizing the bubble behaviour
	class CustomInfoWindow extends MarkerInfoWindow {
		
		private JSONObject obj_balao;
		public CustomInfoWindow(MapView mapView, JSONObject obj) {
			super(R.layout.bonuspack_bubble, mapView);
			obj_balao = obj;
			Button btn = (Button)(mView.findViewById(R.id.bubble_moreinfo));
			TextView title = (TextView) mView.findViewById(R.id.bubble_title);
			TextView desc = (TextView) mView.findViewById(R.id.bubble_description);
			TextView sub = (TextView) mView.findViewById(R.id.bubble_subdescription); 
			try {
				title.setText(obj.getString("titulo"));			
				desc.setText(obj.getString("descricao"));
				sub.setText(obj.getString("nomeLocal"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			btn.setOnClickListener(new View.OnClickListener() {
			    public void onClick(View view) {
			    	
		            Intent myIntent = new Intent(MainActivity.this, Evento.class);
		            
		            Bundle id = new Bundle();
		    		try {
						id.putInt("idEv", obj_balao.getInt("idEvento"));
						Log.d("M.Debug.intentBUBBLE", obj_balao.getString("idEvento"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		    		myIntent.putExtras(id);
		    		view.getContext().startActivity(myIntent);
			    }
			});
		}
		@Override public void onOpen(Object item){
			super.onOpen(item);
			mView.findViewById(R.id.bubble_moreinfo).setVisibility(View.VISIBLE);
			
			//8. put thumbnail image in bubble, fetching the thumbnail in background:
//			if (mSelectedPoi.mThumbnailPath != null){
//				ImageView imageView = (ImageView)mView.findViewById(R.id.bubble_image);
//				mSelectedPoi.fetchThumbnailOnThread(imageView);
//			}
		}	
	}
	
    private class MyAsyncTask extends AsyncTask<String, Integer, JSONArray>{
    	@Override
        protected JSONArray doInBackground(String... params) {	        	
        	Projection prj = map.getProjection();
        	GeoPoint nordeste = (GeoPoint) prj.getNorthEast(), sudoeste = (GeoPoint) prj.getSouthWest();         	
        	
        	String qry= "SELECT * FROM `evento` inner join ( SELECT * FROM `geoPonto` "
        	+ "WHERE `latitute`>= "+ sudoeste.getLatitudeE6() +" AND `latitute`<= "
    				+ nordeste.getLatitudeE6() +" AND `longitude`>= "+sudoeste.getLongitudeE6()+" AND "
        	+ "`longitude`<= "+nordeste.getLongitudeE6()+") as PTS on `evento`.`idGeoPonto` = `PTS`.`idLocal`";
        	
        	
//    		String qry= "SELECT * FROM `geoPonto` WHERE `latitute`>= "+ sudoeste.getLatitudeE6() +" AND `latitute`<= "
//    				+ nordeste.getLatitudeE6() +" AND `longitude`>= "+sudoeste.getLongitudeE6()+" AND `longitude`<= "
//    				+nordeste.getLongitudeE6();    			    		
    		return DbConnection.consulta(qry);	    				        
        }
         
        protected void onPostExecute(JSONArray result){

    			        	
    		plot_points(result);    			  
        }                
        
    }
	
	
	

}
